package micro_demo

import (
	"context"
	httpServer "github.com/asim/go-micro/plugins/server/http/v4" // 特别注意这里"
	"github.com/gin-gonic/gin"
	"go-micro.dev/v4"
	"go-micro.dev/v4/registry"
	"go-micro.dev/v4/server"
	"log"
	"net/http"
	"protobuf/pb"
)

func HttpMicro() error {
	// gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Recovery())

	// register router
	r.POST("/http_micro", func(c *gin.Context) {
		// create a service
		service := micro.NewService()
		service.Init()

		client := pb.NewFutureService("future", service.Client())

		rsp, err := client.GetMinBar(context.Background(), &pb.BarRequest{Instrument: "rb2205"})
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusInternalServerError,
				"msg":  err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  rsp, // 返回 BarResponse
		})
	})

	err := r.Run(":8089")
	return err
}

// HttpMicro2 与 httpMicro 函数相比增加了micro.Registry, 但效果相同
// 问题: 在不启动 micro/server情况下 请求失败
func HttpMicro2() error {
	// create service
	srv := httpServer.NewServer(
		server.Name("future"),
		server.Address(":8088"),
	)

	// gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	r.Use(gin.Recovery())

	// register router
	r.POST("/http_micro", func(c *gin.Context) {
		// create a service
		service := micro.NewService()
		service.Init()

		client := pb.NewFutureService("future", service.Client())

		rsp, err := client.GetMinBar(context.Background(), &pb.BarRequest{Instrument: "rb2205"})
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusInternalServerError,
				"msg":  err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  rsp, // 返回 BarResponse
		})
	})

	hd := srv.NewHandler(r)
	if err := srv.Handle(hd); err != nil {
		log.Fatal(err)
	}

	// create a new service
	service := micro.NewService(
		micro.Server(srv),
		micro.Registry(registry.NewRegistry()),
	)
	service.Init()
	// register handler 报错, 需要注册http.service
	// if err := pb.RegisterFutureHandler(service.Server(), &handler.Future{}); err != nil {
	// 	return err
	// }

	// run service
	err := service.Run()
	return err
}
